package common.kingdee.repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import common.kingdee.domain.KingdeeDepartment;
import common.security.domain.Department;
import common.security.repository.DepartmentLoader;
import common.webtools.MyHttpClient;
import net.sf.json.JSONObject;
@Repository
public class KingdeeDepartmentLoader implements DepartmentLoader{
    private MyHttpClient myHttpClient=new MyHttpClient();
    @Value("${EID}")
    private String EID;
    @Value("${keyFileDir}")
    private String keyFileDir;
    @Value("${host}")
    private String host;
    @Value("${getDepartmentPath}")
    private String getDepartmentPath;
    private KingdeeEncrypt kindeeEncrypt=new KingdeeEncrypt();
    @Override
    public  Set<Department> load() {
		String url = host + getDepartmentPath;
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("eid", EID));
		JSONObject obj = new JSONObject();
		obj.put("eid", EID);
		if(!keyFileDir.endsWith("/")){
			keyFileDir+="/";
		}
		nvps.add(new BasicNameValuePair("data", kindeeEncrypt.encrypt(obj.toString(),keyFileDir+EID+".key")));
		Set<Department> departments=new HashSet<>();
		try {
			String reponse = myHttpClient.post(url, nvps);
			JSONObject jsonObj = JSONObject.fromObject(reponse);
			List<JSONObject> list = (List<JSONObject>)jsonObj.get("data");
			for(JSONObject jSONObject:list){
				String id=(String)jSONObject.get("id");
				String longName=((String)jSONObject.get("department")).replaceAll("\\\\", "/");
				Department department=new KingdeeDepartment(id,longName);
				departments.add(department);
				//System.out.println("longName:"+department.getLongName()+",name:"+department.getName()+",parentLongName:"+department.getParentLongName());
			}
		} catch (IOException | HttpException e) {
			e.printStackTrace();
		}
		return departments;
	}
	@Override
	public Department createEmptyDepartment() {
		return new KingdeeDepartment("","/");
	}
}
